#ifndef ASIO_SERVICE_POOL_H
#define ASIO_SERVICE_POOL_H

#include <boost/asio.hpp>
#include <vector>
#include <memory>
#include <thread>
#include <atomic>
#include <mutex>
#include "../util/singleton.h"

namespace Yizhi {

class AsioServicePool : public Singleton<AsioServicePool> {
    friend class Singleton<AsioServicePool>;
    
public:
    typedef boost::asio::io_context IOService;
    typedef IOService::work Work;
    typedef std::unique_ptr<Work> WorkPtr;

    // 启动服务池
    void start();
    
    // 停止服务池
    void stop();
    
    // 获取IO服务（轮询方式）
    IOService& GetIoservice();
    
    // 获取最少负载的IO服务
    IOService& GetLeastLoadedIoservice();
    
    // 获取池大小
    size_t size() const { return m_ioservices.size(); }
    
    // 检查是否正在运行
    bool is_running() const { return m_running; }
    
    

private:
    AsioServicePool(size_t size =2);
    ~AsioServicePool();
    
    // 禁止拷贝和赋值
    AsioServicePool(const AsioServicePool&) = delete;
    AsioServicePool& operator=(const AsioServicePool&) = delete;

private:
    std::vector<std::unique_ptr<IOService>> m_ioservices;
    std::vector<WorkPtr> m_works;
    std::vector<std::thread> m_threadpool;
    std::atomic<size_t> m_nextService;
    std::atomic<bool> m_running{false};
    std::mutex m_mutex;
};

} // namespace Yizhi

#endif // ASIO_SERVICE_POOL_H